package com.maple.sharding.config.sharding.order;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;

@Component
public class TableComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm {

    @Override
    public Collection<String> doSharding(Collection collection, ComplexKeysShardingValue shardingValues) {

        System.out.println("collection:" + JSONObject.toJSONString(collection) + ",shardingValues:" + JSONObject.toJSONString(shardingValues));

        Collection<String> routeTables = new ArrayList<>();

        Collection<String> tables = collection;

        String shardingValue = getShardingValue(shardingValues);

        routeTables.add(tables.stream().filter((table) -> table.endsWith(shardingValue)).findFirst().get());

        return routeTables;
    }

    /**
     * 获取倒数2~3位
     *
     * @return
     */
    private String getShardingValue(ComplexKeysShardingValue shardingValues) {

        Map<String, LinkedList<String>> columnNameAndShardingValuesMap = shardingValues.getColumnNameAndShardingValuesMap();

        for (Map.Entry<String, LinkedList<String>> entry : columnNameAndShardingValuesMap.entrySet()) {

            //20210908745
            String tempShardingValue = entry.getValue().get(0);

            //74
            String shardingValue = StringUtils.substring(tempShardingValue, tempShardingValue.length() - 3, tempShardingValue.length() - 1);

            //74 表
            return shardingValue;
        }
        return null;
    }
}
